from PyQt5.QtWidgets import QMessageBox, QDialog
from PyQt5.QtCore import QStringListModel, QDate
import UI.item_editor_UI as item_editor_UI
import json
from SingleLog import SingleLog
from queue import Queue


class ItemEditorUI(QDialog, item_editor_UI.Ui_Dialog):
    def __init__(self, is_out=False):
        super(ItemEditorUI, self).__init__()
        self.setupUi(self)
        self.is_out = is_out
        self.dataList = []
        self.typeData = []
        if self.is_out:
            self.setWindowTitle('出库')
            self.unitPriceLabel.close()
            self.unitPriceLineEdit.close()
        else:
            self.setWindowTitle('入库')
        try:
            with open('typeData.json', 'r') as f:
                self.typeData = json.load(f)
            with open('logData.json', 'r') as f:
                self.dataList = json.load(f)
        except json.JSONDecodeError as err:
            print('JSONDecodeError: {0}'.format(err))
        except IOError as err:
            print('IOError: {0}'.format(err))
        self.typeModel = QStringListModel(self)
        self.typeModel.setStringList(self.typeData)
        self.comboBox.setModel(self.typeModel)
        self.dateEdit.setDate(QDate.currentDate())

    def add(self):
        mode = 1
        u = self.unitLineEdit.text()
        up = self.unitPriceLineEdit.text()
        num = self.numberLineEdit.text()
        date = self.dateEdit.date().toString('yyyy/MM/dd')
        if self.is_out:
            up = '-1'
            mode = -1
        try:
            item_type = self.typeData[self.comboBox.currentIndex()]
        except IndexError as err:
            print('IndexError: {0}'.format(err))
            QMessageBox.critical(self, '错误', '你还没有选择任何货物类型!', QMessageBox.Ignore, QMessageBox.Ignore)
            return
        if item_type == '' or date == '' or u == '':
            QMessageBox.critical(self, '错误', "检查表单填写是否完整!", QMessageBox.Ignore, QMessageBox.Ignore)
            return
        try:
            up = float(up)
            num = float(num)
        except ValueError as err:
            QMessageBox.critical(self, '错误', '检查数据填写是否正确', QMessageBox.Ignore, QMessageBox.Ignore)
            print("ValueError: {0}".format(err))
            return
        if not self.is_out:
            self.dataList.append(SingleLog(item_type, u, num, up, date, mode).dict)
        elif up == -1:
            data_in_queue = Queue()
            data_out = float(0)
            for item in self.dataList:
                if item['kind'] == item_type and item['mode'] == 1:
                    data_in_queue.put(item)
                if item['kind'] == item_type and item['mode'] == -1:
                    data_out += item['number']
            di_queue = Queue()
            while data_out != 0 and (not data_in_queue.empty()):
                dt = data_in_queue.get()
                data_temp = SingleLog(dt['kind'], dt['unit'], dt['number'], dt['unitPrice'],
                                      dt['date'], dt['mode']).dict
                if data_out > data_temp['number']:
                    data_out -= data_temp['number']
                else:
                    data_temp['number'] -= data_out
                    if data_temp['number'] != 0:
                        di_queue.put(data_temp)
                    data_out = 0
            while not data_in_queue.empty():
                di_queue.put(data_in_queue.get())
            data_in_queue = di_queue
            data_out = num
            while data_out != 0 and (not data_in_queue.empty()):
                data_temp = data_in_queue.get()
                if data_out > data_temp['number']:
                    self.dataList.append(
                        SingleLog(item_type, u, data_temp['number'], data_temp['unitPrice'], date, mode).dict)
                    data_out -= data_temp['number']
                else:
                    self.dataList.append(SingleLog(item_type, u, data_out, data_temp['unitPrice'], date, mode).dict)
                    data_out = 0
            if data_out != 0:
                QMessageBox.critical(self, '错误', '出库数量超过库存数量,检查数据填写', QMessageBox.Ignore, QMessageBox.Ignore)
                self.close()
                return
        self.save()
        self.close()

    def refresh(self):
        self.unitLineEdit.setText('')
        try:
            t = self.typeData[self.comboBox.currentIndex()]
        except IndexError as err:
            print('IndexError: {0}'.format(err))
            return
        flag = True
        for item in self.dataList:
            if item['kind'] == t:
                self.unitLineEdit.setText(item['unit'])
                flag = False
                break
        self.unitLineEdit.setEnabled(flag)

    def save(self):
        try:
            with open('logData.json', 'w') as f:
                json.dump(self.dataList, f)
        except json.JSONDecodeError as err:
            print('JSONDecodeError: {0}'.format(err))
        except IOError as err:
            print('IOError: {0}'.format(err))
